import random
import string
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, String, Text,TIMESTAMP

db = SQLAlchemy()


class Code(db.Model):
    open_id = Column(String(30), index=True)
    code = Column(String(8), primary_key=True)
    create_time = Column('create_time', TIMESTAMP)

    def __init__(self, open_id):
        self.create_time = datetime.now()
        self.open_id = open_id
        while True:
            self.code = ''.join(random.sample(string.ascii_uppercase + '1234567890', 8))
            if not Code.query.filter_by(code=self.code).first():
                break


class CourseData(db.Model):
    create_time = Column('create_time', TIMESTAMP)
    open_id = Column(String(30), primary_key=True)
    data = Column(Text)
    stu_id = Column(String(10), nullable=True)

    def __init__(self, open_id, data, stu_id=None):
        self.create_time = datetime.now()
        self.open_id = open_id
        self.data = data
        self.stu_id = stu_id
